import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import prismaClient from '@/config/prismaClient';
import { throwHttpException1 } from '@/utils/nesjUtils';

// 校验入参
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    // 2、校验必填参数是否传递
    const requiredFields = [
      { name: 'ID', field: 'ID' },
      { name: '密码', field: 'Name' },
      { name: '手机号', field: 'Phone' },
      { name: '邮箱', field: 'Email' },
      { name: '头像Url', field: 'AvatarUrl' },
      { name: '生日', field: 'Birthday' },
      { name: '性别', field: 'Gender' },
      { name: '省份编码', field: 'ProvienceCode' },
      { name: '城市编码', field: 'CityCode' },
      { name: '县编码', field: 'CountyCode' },
      { name: '备注', field: 'Note' },
    ];
    const bodyKeys = Object.keys(req.body);
    const errFields = requiredFields.filter((f) => {
      if (!bodyKeys.includes(f.field)) {
        return f;
      }
    });

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }

    next();
  }
}

@Injectable()
class CheckIDIsExistMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    const errRows = [];
    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        ID: req.body.ID,
        IsDel: '0',
      },
    });
    if (baseUserList.length == 0) {
      errRows.push(req.body.ID);
    }

    if (errRows.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！以下ID未找到: ${errRows.join()}`,
        data: '',
      });
    }

    next();
  }
}

export default {
  CheckParamIsEmptyMiddleware,
  CheckIDIsExistMiddleware,
};
